package com.supplychain.financial.parent.common.util;

import com.supplychain.financial.parent.common.emchat.Emchat;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 小云发消息的工具
 * @author zhengchuan
 *
 */
public class SendMessageUtils {
	private static final Logger log = LoggerFactory.getLogger(SendMessageUtils.class);
	/**
	 * List<Map<String,Object> : [{cloudingId=-1 , users=[12,23]},{cloudingId=-2 , users=[22,33]}]
	 * String type : 文字 : "text" , 图片: "image"
	 * jsonObject  : 文字 :  obj.put("msgContent",content); 
	 *               图片 :  obj.put("imgUrl",imgUrl);
	 *                       obj.put("title", title1);
	 *			 			 obj.put("summary",title2);
	 *			 			 obj.put("linkUrl",linkUrl);
	 *			 			 obj.put("date", date);
	 * @throws InterruptedException
	 */
	public static void sendMessage(List<Map<String,Object>> cloudingAndUsersList ,JSONObject message ,String type,String faSongFang) throws InterruptedException{
		String context = "";
		Map<String,String> map = null;
		if(type.equals("text")){
			context = message.getString("msgContent");
		}else if(type.equals("image")){
			context = message.getString("title");
			map = new HashMap<>();
			map.put("action", "ad");
			map.put("type", "image_and_text");
			map.put("data", message.toString());
		}
		for (Map<String, Object> cloudingAndUsers : cloudingAndUsersList) {
			String cloudingId =  cloudingAndUsers.get("cloudingId").toString();
			if ("005".equals(faSongFang)){
				cloudingId = "-1";
			}
			if ("007".equals(faSongFang)){
				cloudingId = "-7";
			}
			if ("-66".equals(faSongFang)){
				cloudingId = "-66";
			}
			List<String> userIds =  (List<String>) cloudingAndUsers.get("users");
			log.info( "{小云：" + cloudingId + "的好友有："+ userIds + "}");
			List<String[]> userIdArrays = new ArrayList<>(); //存放20个一组userID的对象
			int totle = (userIds.size() % 20 == 0) ? userIds.size() / 20 : (userIds.size() / 20 + 1);
			for (int k = 1; k <= totle; k++) {
				if (k < totle) {
					String[] usersArray = new String[20];
					userIds.subList(20 * (k - 1), 20 * k).toArray(usersArray);
					userIdArrays.add(usersArray);
				}else{
					String[] usersArray = new String[userIds.subList(20 * (k - 1), userIds.size()).size()];
					userIds.subList(20 * (k - 1), userIds.size()).toArray(usersArray);
					userIdArrays.add(usersArray);
				}
			}
			for (String[] strings : userIdArrays) {
				String strs =  Arrays.toString(strings);
				String emchat = Emchat.sendBatchTextMessage(cloudingId, context, strings, map);
				//String emchat = "ok";
				log.info(String.format("[小云:%s] [发送状态:%s] [内容:%s] {userId:%s} [map:%s]",cloudingId,emchat,context,strs,map));
				if(!"ok".equals(emchat)){
					log.error("小云：" + cloudingId + " 发送消息失败，失败信息：[ " + emchat + " ]， 失败用户ID：" + strs);
				/*	try {
						SimpleDateFormat df = new SimpleDateFormat("yyyMMDD");//设置日期格式
						String page_name = df.format(new Date());
						String filePath = path+"\\logs\\"+page_name+".txt";
						File file = new File(filePath);
						FileOperation.createFile(file);
						String content = "["+new Date()+"] [小云:"+cloudingId+"] {userId:"+strs+"}";
						FileOperation.contentToTxt(filePath, content);
					} catch (Exception e) {
						e.printStackTrace();
					}*/
				}
				Thread.sleep(1500);
			}
		}
	}

	public static String generateHtml(String contentText) {
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//设置日期格式
		String page_name = df.format(new Date());
		//测试
//		String file_path = "/u01/web/download/page/"+page_name+".html";
		//正式
		String file_path = "/u01/web/page/cloudling/"+page_name+".html";
//		String file_path = "/User/zhengchuan/"+page_name+".html";
		File file = new File(file_path);
		String top = "<!DOCTYPE html>" + "<html>" + "<head>"
				+ "<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>"
				+ "<meta http-equiv='X-UA-Compatible' content='IE=edge'>"
				+ "<meta name='viewport' content='width=device-width, initial-scale=1.0,maximum-scale=1.0,user-scalable=no'>"
				+ "<title></title>"
				+ "<style>img{max-width: 100%;max-height: 100%; align-content: center;}</style>"
				+ "<script src='scripts/jquery-2.1.4.min.js'></script>"
				+ "<script type='text/javascript'>$(function() {"
				+ "$('a').click("
				+ "function jsFunction(){"
				+ "window.location.href = $('a').attr('href');android.jsFunction();"
				+ "})});"
				+ "</script>"
				+ "<body>";
		String bottom = "</body></html>";
		try (FileOutputStream fop = new FileOutputStream(file, true)) {
			// if file doesn't exists, then create it
			if (!file.exists()) {
				log.info(file_path + "文档不存在        正在为你创建.....................");
				file.createNewFile();
				log.info("创建" + file_path + " 文档成功");
			}
			// get the content in bytes
			byte[] topInBytes = top.getBytes();
			byte[] contentInBytes = contentText.getBytes();
			byte[] bottomInBytes = bottom.getBytes();
			fop.write(topInBytes);
			fop.write(contentInBytes);
			fop.write(bottomInBytes);
			fop.flush();
			fop.close();

			log.info("html 页面生成成功");
		//测试
//			log.error(String.format("[linkUrl:%s]", "http://test.combinedpay.cn:28100/download/page/"+page_name+".html"));
//			return "http://test.combinedpay.cn:28100/download/page/"+page_name+".html";
			//正式
			log.info(String.format("[linkUrl:%s]", "http://clouderp.combinedpay.cn:20080/web/page/cloudling/"+page_name+".html"));
			return "http://ktyt.skystorechain.com:20080/web/page/cloudling/"+page_name+".html";
		} catch (IOException e) {
			log.error("html 页面生成失败,失败信息："+e.getMessage());
			e.printStackTrace();
			return null;
		}

	}

}
